﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System.Collections.Specialized;

namespace GetHistory
{
    enum Connection
    {
        Cancelled,
        Connected,
        Failed
    }

    public partial class GetHistoryForm : Form
    {
        private TfsTeamProjectCollection TfsCollection { get; set; }
        private WorkItemStore wis;
        TeamProjectPicker tfsPP;

        public GetHistoryForm()
        {
            InitializeComponent();
            if (connectToTFS() == Connection.Cancelled)
            {
                Environment.Exit(2);
            }
        }

        #region Properties

        public bool IsColumnFilterDirty { get; set; }

        public Project SelectedProject
        {
            get
            {
                return wis.Projects[projectComboBox.SelectedItem.ToString()];
            }
        }

        #endregion

        private Connection connectToTFS()
        {
            Connection result = Connection.Failed;
            tfsPP = new TeamProjectPicker(TeamProjectPickerMode.MultiProject, false, new UICredentialsProvider());
            this.projectComboBox.SelectedIndexChanged -= new System.EventHandler(this.projectComboBox_SelectedIndexChanged);
            while (result == Connection.Failed)
            {
                if (tfsPP.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                {
                    result = Connection.Cancelled;
                }
                else
                {
                    TfsCollection = tfsPP.SelectedTeamProjectCollection;
                    TfsCollection.EnsureAuthenticated();
                    if (tfsPP.SelectedProjects.Length < 1)
                    {
                        MessageBox.Show("Select one or more projects", "Get History");
                        result = Connection.Failed;
                    }
                    else if (TfsCollection.HasAuthenticated)
                    {
                        result = Connection.Connected;
                        clear();

                        wis = TfsCollection.GetService<WorkItemStore>();
                        projectComboBox.Items.Clear();
                        for (int i = 0; i < tfsPP.SelectedProjects.Length; i++)
                        {
                            projectComboBox.Items.Add(tfsPP.SelectedProjects[i]);
                        }
                        projectComboBox.SelectedIndex = 0;
                        GetWorkItemFields();
                        LoadQueries();
                        IsColumnFilterDirty = false;
                    }
                }
                this.projectComboBox.SelectedIndexChanged += new System.EventHandler(this.projectComboBox_SelectedIndexChanged);
            }

            return result;
        }

        private void PopulateWorkItems(QueryDefinition qd)
        {
            WorkItemListView.Items.Clear();
            string q = qd.QueryText;
            q = q.Replace("@project", "'" + SelectedProject.Name + "'").Replace("@Me", "'" + Environment.UserName + "'");
            foreach (WorkItem wi in wis.Query(q))
            {
                ListViewItem lvi = new ListViewItem(wi.Id.ToString());
                lvi.Tag = wi;
                lvi.SubItems.Add(wi.Title);
                WorkItemListView.Items.Add(lvi);
            }
        }

        private void exportToExcel()
        {
            CreateExcelDoc export = new CreateExcelDoc(historyTab);
        }

        #region Clear Controls

        private void clear()
        {
            clearHistory();
            clearWorkItems();
            clearWorkItemQueries();
            excelExportButton.Enabled = false;
        }

        private void clearHistory()
        {
            foreach (TabPage tp in historyTab.TabPages)
            {
                historyTab.TabPages.RemoveByKey(tp.Name);
            }
        }

        private void clearWorkItemQueries()
        {
            QueriesTreeView.Nodes.Clear();
        }

        private void clearWorkItems()
        {
            WorkItemListView.Items.Clear();
        }

        #endregion

        #region Control Events

        #region Buttons

        private void closeButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void connectButton_Click(object sender, EventArgs e)
        {
            connectToTFS();
        }

        private void excelExportButton_Click(object sender, EventArgs e)
        {
            exportToExcel();
        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            clear();
            LoadQueries();
        }


        #endregion

        #region Ignore Tab

        private void GetWorkItemFields()
        {
            this.ignoreListBox.ItemCheck -= new System.Windows.Forms.ItemCheckEventHandler(this.ignoreListBox_ItemCheck);
            foreach (FieldDefinition wiField in wis.FieldDefinitions)
            {
                if (Properties.Settings.Default.Ignore.Contains(wiField.Name))
                {
                    ignoreListBox.Items.Add(wiField.Name, CheckState.Checked);
                }
                else
                {
                    ignoreListBox.Items.Add(wiField.Name, CheckState.Unchecked);
                }
            }
            this.ignoreListBox.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.ignoreListBox_ItemCheck);
        }

        private void ignoreListBox_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            string item = ignoreListBox.Items[e.Index].ToString();
            if (e.NewValue == CheckState.Checked)
            {
                Properties.Settings.Default.Ignore.Add(item);
            }
            else
            {
                Properties.Settings.Default.Ignore.Remove(item);
            }
            Properties.Settings.Default.Save();
            IsColumnFilterDirty = true;
        }

        private void selectAllCheckBox_CheckedChanged(object sender, EventArgs e)
        {

            if (selectAllCheckBox.Checked == true)
            {
                for (int i = 0; i < ignoreListBox.Items.Count; i++)
                {
                    if (!ignoreListBox.GetItemChecked(i))
                        ignoreListBox.SetItemChecked(i, true);
                }
            }
            else
            {
                for (int i = 0; i < ignoreListBox.Items.Count; i++)
                {
                    if (ignoreListBox.GetItemChecked(i))
                        ignoreListBox.SetItemChecked(i, false);
                }
            }
            IsColumnFilterDirty = true;
        }

        #endregion

        private void projectComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadQueries();
        }

        private void QueriesTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            QueryItem qi = e.Node.Tag as QueryItem;
            if (qi is QueryFolder)
            {
                WorkItemListView.Items.Clear();
            }
            else
            {
                this.WorkItemListView.ItemChecked -= new System.Windows.Forms.ItemCheckedEventHandler(this.WorkItemListView_ItemChecked);
                PopulateWorkItems(qi as QueryDefinition);
                clearHistory();
                this.WorkItemListView.ItemChecked += new System.Windows.Forms.ItemCheckedEventHandler(this.WorkItemListView_ItemChecked);
            }
        }

        private void WorkItemListView_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (e.Item.Checked)
            {
                createHistoryTab(e.Item.Tag as WorkItem);
            }
            else
            {
                removeHistoryTab(e.Item.Text);
            }
        }

        #endregion

        private void LoadQueries()
        {
            clearWorkItemQueries();
            foreach (QueryItem queryItem in SelectedProject.QueryHierarchy)
            {
                GetNodesForQueryFolder(queryItem as QueryFolder, QueriesTreeView.Nodes);
            }
        }

        private void GetNodesForQueryFolder(QueryFolder queryFolder, TreeNodeCollection nodes)
        {
            TreeNode folderNode = new TreeNode(queryFolder.Name);
            folderNode.Tag = queryFolder;
            nodes.Add(folderNode);

            foreach (QueryItem queryItem in queryFolder)
            {
                if (queryItem is QueryFolder)
                {
                    GetNodesForQueryFolder(queryItem as QueryFolder, folderNode.Nodes);
                }
                else
                {
                    TreeNode itemNode = new TreeNode(queryItem.Name);
                    itemNode.Tag = queryItem;
                    folderNode.Nodes.Add(itemNode);
                }
            }
        }

        private void removeHistoryTab(string text)
        {
            historyTab.TabPages.Remove(historyTab.TabPages[text]);
        }

        private void createHistoryTab(WorkItem wi)
        {
            HistoryData hd = new HistoryData();
            hd.PopulateHistory(wi);
            hd.Dock = DockStyle.Fill;

            TabPage tab = new TabPage(wi.Id.ToString());
            tab.Name = wi.Id.ToString();
            tab.ToolTipText = wi.Title;
            tab.Controls.Add(hd);

            this.historyTab.TabPages.Add(tab);
            excelExportButton.Enabled = true;
        }

        private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
        {
                if (IsColumnFilterDirty)
                {
                    clearHistory();
                    foreach (ListViewItem lvi in WorkItemListView.CheckedItems)
                    {
                        createHistoryTab(lvi.Tag as WorkItem);
                    }
                    IsColumnFilterDirty = false;
                }
        }

 
    }
}
